package com.caoJun.annotation_aspectJ.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * @Description: 切面类，在此类中编写通知
 * @Author 83-start
 * @Time 2021/4/20 14:45
 */
@Aspect
@Component
public class MyAspect {
    /**
     * 定义切入点表达式
     */
    @Pointcut("execution(* com.caoJun.annotation_aspectJ.dao.UserDao.*(..))")
    private void myPointCut() {
    }

    /**
     * 前置通知
     *
     * @param joinPoint
     */
    @Before("myPointCut()")
    public void myBefore(JoinPoint joinPoint) {
        System.out.print("前置通知:模拟执行检查 ...,");
        System.out.print("目标类是:" + joinPoint.getTarget());
        System.out.print(",被植入增强处理的的目标为:" + joinPoint.getSignature().getName());
    }

    /**
     * 后置通知
     *
     * @param joinPoint
     */
    @AfterReturning("myPointCut()")
    public void myAfterReturning(JoinPoint joinPoint) {
        System.out.print("后置通知:模拟记录日志 ...,");
        System.out.print("被植入增强处理的目标方法为:" + joinPoint.getSignature().getName());
    }

    /**
     * 环绕通知
     *
     * @param proceedingJoinPoint
     * @return
     */
    @Around("myPointCut()")
    public Object myAround(ProceedingJoinPoint proceedingJoinPoint) {
        // 定义执行方法对象
        Object proceed = null;

        // 开始
        System.out.println("环绕开始:执行目标方法之前，模拟开启事务……");
        // 执行当前的目标方法
        try {
            proceed = proceedingJoinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        // 结束
        System.out.println("环绕结束:执行目标方法之后，模拟关闭事务……");

        return proceed;
    }

    /**
     * 异常通知
     *
     * @param joinPoint
     * @param e
     */
    @AfterThrowing(value = "myPointCut()",throwing = "e")
    public void myAfterThrowing(JoinPoint joinPoint, Throwable e) {
        System.out.println("异常通知:出错了" + e.getMessage());
    }

    /**
     * 最终通知
     */
    @After("myPointCut()")
    public void myAfter() {
        System.out.println("最终通知:模拟方法在结束后释放资源……");
    }

}
